#!/bin/bash
# wsl安装脚本，将安装以下软件：
# nginx 最新稳定版
# php 7.3
# mysql 8.0
# composer 2.0
# redis
# node
# yarn
# supervisor
# crontab
# History:
## 2020/11/01 by  wesen

#vim粘贴错行？粘贴前输入 :set paste  关闭自动缩进，粘贴后再 :set nopaste

cd ~

echo -n "请输入你的非root用户名: "
read user
echo "安装成功后，使用$user修改composer源"

echo -n "请输入laravel项目的根目录(不带后/):"
read wwwPath
if [ ! -n $wwwPath ]; then
       $wwwPath='/path/to/your/app'
fi
echo "项目配置文件地址将填写到 $wwwPath"

####################################
###       备份并修改apt源         ###
####################################

cp /etc/apt/sources.list /etc/apt/sources.list.bak
sed -i 's/http:\/\/archive.ubuntu.com\/ubuntu/http:\/\/mirrors.163.com\/ubuntu/g' /etc/apt/sources.list
sed -i 's/http:\/\/security.ubuntu.com\/ubuntu/http:\/\/mirrors.163.com\/ubuntu/g' /etc/apt/sources.list

#更新apt
apt update && apt -y upgrade


####################################
###      安装最新版的nginx        ###
####################################
echo "deb http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -

sudo apt update && sudo apt install nginx

#解决 invalid PID number问题
nginx -c /etc/nginx/nginx.conf

# wsl tcp bug fastcgi_buffering off;
 cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

grep "fastcgi_buffering off;" /etc/nginx/nginx.conf >/dev/null

if [ $? -ne 0 ]; then
     sed -i 's/sendfile on;/&\n\tfastcgi_buffering off;/' /etc/nginx/nginx.conf
fi

#添加www用户
/usr/sbin/groupadd -f www
/usr/sbin/useradd -g www www

#将执行用户设置成www
grep "user " /etc/nginx/nginx.conf
sed -i 's/user  nginx/user  www www/g' /etc/nginx/nginx.conf
grep "user " /etc/nginx/nginx.conf

chown -R www:www /var/log/nginx
#chown -R  www:www /var/lib/nginx
service nginx restart

#添加示例nginx配置文件
cat>/etc/nginx/conf.d/wesen.conf.example<<EOF
server {
    listen 8080;
    server_name _ ;
    root ${wwwPath}/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;

    index index.php ;

    charset utf-8;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        root           ${wwwPath}/public;
        fastcgi_pass   unix:/run/php/php7.3-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
        include        fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
EOF

####################################
###     安装mysql8.0、redis      ###
####################################
apt install -y mysql-server mysql-client redis libpng-dev
sudo usermod -d /var/lib/mysql/ mysql #使用usermod命令来重新定位mysql所在的目录
#sudo vim /etc/mysql/debian.cnf     #进入mysql文件查看原始密码
#use mysql；
#ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新密码';
#FLUSH PRIVILEGES;


####################################
###  安装supervisor、crontab     ###
####################################
#安装supervisor
sudo apt install supervisor

cat>/etc/supervisor/conf.d/laravel-worker.conf.example<<EOF
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
#命令行路径，自行修改
command=php ${wwwPath}/artisan queue:work --tries=3
autostart=true
autorestart=true
user=nginx
numprocs=8
redirect_stderr=true
#日志文件路径，自行修改
stdout_logfile=${wwwPath}/storage/logs/supervisor/laravel-queue.log
EOF

#创建supervisor启动服务
cat>/usr/lib/systemd/system/supervisord.service<<EOF
# supervisord service for systemd (CentOS 7.0+)
# by ET-CS (https://github.com/ET-CS)
[Unit]
Description=Supervisor daemon

[Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisor/supervisord.conf //指定启动的配置文件
ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown
ExecReload=/usr/bin/supervisorctl $OPTIONS reload
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target
EOF

#安装crontab
apt install cron
#if [ ! -n $wwwPath ]; then
#echo "* * * * * cd ${wwwPath} && php artisan schedule:run >> /dev/null 2>&1" >> /var/spool/cron/$user
#fi



####################################
###       安装node、yarn         ###
####################################

# 下载新版本的node,apt的源太老了
wget https://npm.taobao.org/mirrors/node/v12.18.3/node-v12.18.3-linux-x64.tar.xz
#解压到opt目录下
 tar -xJf node-v12.18.3-linux-x64.tar.xz  -C /opt
#删除node压缩文件
rm -f node-v12.18.3-linux-x64.tar.xz
#建立node和npm的链接
ln -s /opt/node-v12.18.3-linux-x64/bin/node /usr/bin/node
ln -s /opt/node-v12.18.3-linux-x64/bin/npm /usr/bin/npm
#设置npm淘宝镜像
npm config set registry https://registry.npm.taobao.org

#安装yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt -y install yarn

yarn config set registry https://registry.npm.taobao.org

#######################################
###创建自启sh，自启后切换到非root用户 ###
#######################################

#创建自启sh，自启后切换到非root用户
cat>startservers.sh<<EOF
#!/bin/bash
# Edit this for your relevant services.
services=(php7.3-fpm nginx redis-server mysql supervisord cron)
for service in "\${services[@]}"
do
    if (( \$(ps -ef | grep -v grep | grep \$service | wc -l) == 0 ))
    then
    # Uncomment to get messages. #
    #echo "Starting service \${service}"
    (sudo service \$service start > /dev/null &)
    fi
done

for((time=3;time>0;time--))
do
    echo -ne "\$time后自动返回$user用户       \r"
    sleep 1
done
su $user
EOF

#给与权限及添加到.bashrc中
chmod +x startservers.sh;sed -i '$a ~/startservers.sh' .bashrc;

#将root设置为默认用户，以便启动时启动服务，然后切换回非root用户目录,需要在CMD中执行
#C:\Users\用户名\AppData\Local\Microsoft\WindowsApps\ubuntu2004.exe config --default-user root


#######################################
###        安装php和composer        ###
#######################################
#修改php安装源
apt -y install software-properties-common apt-transport-https lsb-release ca-certificates
sudo apt-get update
sudo LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php
sudo apt-get update

#安装php7.3及其扩展
apt install -y php7.3  php7.3-fpm php7.3-mbstring php7.3-mysql  php7.3-curl  php7.3-xml php7.3-zip php7.3-gd php7.3-dev  php7.3-bcmath  php7.3-xmlrpc php7.3-opcache php7.3-json php7.3-pgsql php7.3-redis php7.3-mongodb

# for safe cgi.fix_pathinfo=0  7.3已经默认为falsel
# cp /etc/php/7.3/fpm/php.ini /etc/php/7.3/fpm/php.ini.bak
# sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/' /etc/php/7.3/fpm/php.ini

#修改php-fom用户

sed -i 's/user = www-data/user = www/g'  /etc/php/7.3/fpm/pool.d/www.conf
sed -i 's/group = www-data/group = www/g'  /etc/php/7.3/fpm/pool.d/www.conf

service php7.3-fpm restart

#安装composer 2.0

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/bin/composer
chmod +x /usr/bin/composer

#用其他用户设置composer镜像
su - $user -c "composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/"

